<template>
  <lay-col :md="24">
    <lay-card>
      <lay-form :model="queryModel" style="margin-top: 20px" ref="layFormRef">
        <lay-row>
          <lay-col :md="4">
            <lay-input v-model="queryModel.userName" style="width: 90%" placeholder="根据用户名搜索"></lay-input>
          </lay-col>
          <lay-col :md="4">
            <lay-input v-model="queryModel.nickName" style="width: 90%" placeholder="根据姓名搜索"></lay-input>
          </lay-col>
          <lay-col :md="4">
            <lay-select v-model="queryModel.status" placeholder="用户状态">
              <lay-select-option value="1" label="启用"></lay-select-option>
              <lay-select-option value="0" label="禁用"></lay-select-option>
            </lay-select>
          </lay-col>
          <lay-col :md="3">
            <lay-form-item label-width="0">
              <lay-button type="primary" @click="GetList(queryModel)">查询</lay-button>
              <lay-button @click="reset">重置</lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>
  </lay-col>
  <lay-col :md="24">
    <lay-card>
      <lay-table :page="page" :columns="columns" :dataSource="dataSource" :default-toolbar="defaultToolbar"
        v-model:selectedKeys="selectedKeys" @change="change" :size="tablesize">
        <template v-slot:toolbar>
          <lay-button type="primary" size="sm" @click="add" v-permission="PerKey.UserDept_AddOrEditView">新增用户
          </lay-button>
        </template>
        <template v-slot:logininfo="{ data }">
          {{data.loginip}} <br> {{data.logintime}}
        </template>
        <template v-slot:nickname="{ data }">
          {{data.nickname}} <br> {{data.phone}}
        </template>
        <template v-slot:postName="{ data }">
          {{data.postName}} <br>({{data.postCode}})
        </template>
        <template v-slot:userinfo="{ data }">
          <lay-avatar :src="avatar(data.avatar)" radius></lay-avatar>
        </template>
        <template v-slot:sex="{ data }">
          {{data.sex==1?"男":"女"}}
        </template>
        <template v-slot:stat="{ data }">
          <lay-switch v-model="data.status" onswitch-text="启用" unswitch-text="禁用"
            @change="changeStatus($event,data.id)"></lay-switch>
        </template>
        <template v-slot:operator="{ data }">
          <lay-button-group>
            <lay-button type="primary" size="sm" @click="edit(data.id)" v-permission="PerKey.UserDept_AddOrEditView">编辑
            </lay-button>
            <lay-button type="danger" size="sm" @click="del(data)" v-permission="PerKey.UserDept_Delete">删除</lay-button>
          </lay-button-group>
        </template>
      </lay-table>
    </lay-card>
  </lay-col>

  <lay-layer :title="addoredittip" v-model="modelVisible" resize="true" :area="['1200px','500px']"
    :offset="['40%','50%']">
    <lay-card style="padding:10px;">
      <lay-row space="10">
        <lay-form :model="form">
          <lay-col md="7">
            <lay-form-item label="所属部门" prop="deptId" required>
              <lay-select v-model="form.deptId">
                <lay-select-option v-for="dept in userDepts" :value="dept.id" :label="dept.deptName">
                </lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col md="7">
            <lay-form-item label="岗位" prop="postId" required>
              <lay-select v-model="form.postId">
                <lay-select-option v-for="post in userPosts" :value="post.id"
                  :label="post.postName+' - '+post.postCode">
                </lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col md="7">
            <lay-form-item label="角色" prop="gid" required>
              <lay-select v-model="form.gid">
                <lay-select-option v-for="group in userGroups" :value="group.id" :label="group.groupname">
                </lay-select-option>
              </lay-select>
            </lay-form-item>
          </lay-col>
          <lay-col :md="24" style="margin-top:30px;">
            <lay-form-item label="用户名" prop="username" required required-error-message="用户名不能空">
              <lay-col md="8">
                <lay-input v-model="form.username"></lay-input>
              </lay-col>
            </lay-form-item>

            <lay-form-item label="姓名" prop="nickname">
              <lay-col md="6">
                <lay-input v-model="form.nickname"></lay-input>
              </lay-col>
              <lay-col md="6" class="tip">姓名为中文</lay-col>
            </lay-form-item>
            <lay-form-item label="密码" prop="password">
              <lay-col md="6">
                <lay-input v-model="form.password"></lay-input>
              </lay-col>
              <lay-col md="18" class="tip">新增用户密码不能为空，修改用户密码不修改空着就行了</lay-col>
            </lay-form-item>
            <lay-form-item label="用户状态" prop="status">
              <lay-col md="6" class="tip">
                <lay-switch v-model="form.status" onswitch-text="启用" unswitch-text="禁用"></lay-switch>
              </lay-col>
              <lay-col md="6"> </lay-col>
            </lay-form-item>
            <lay-form-item>
              <lay-button @click="submitClick" type="primary" v-permission="PerKey.UserPost_AddOrEdit">
                {{addoredittip}}
              </lay-button>
            </lay-form-item>

          </lay-col>
        </lay-form>
      </lay-row>
    </lay-card>

  </lay-layer>

</template>
  
<script lang="ts" setup>
import { reactive, ref, toRefs, watch } from "vue";
import { layer } from "@layui/layer-vue";
import { getList, delOne, chStatus, postAdd, putEdit, getEdit } from "../../../api/module/user/user";
import { PerKey } from "../../../library/permissionConst"
import { useRoute, useRouter } from "vue-router";
import { uploadConfig } from "../../../api/upload"
import { User } from '../../../types/user'
const selectedKeys = ref(["1"]);
const defaultToolbar = ref(true);
const page = ref({ total: 0, limit: 10, current: 1 });
const tablesize = ref('md');
const router = useRouter();
const columns = [
  {
    title: "Id",
    width: "50px",
    key: "id", align: "center",
  }, {
    title: "用户名",
    width: "80px",
    key: "username", align: "center",
  }, {
    title: "姓名",
    width: "120px",
    customSlot: "nickname", align: "center",
  }, {
    title: "部门",
    width: "100px",
    key: "deptName", align: "center",
  }
  , {
    title: "职务",
    width: "120px",
    customSlot: "postName",
    align: "center",
  }
  , {
    title: "角色",
    width: "120px",
    key: "groupname", align: "center",
  }
  , {
    title: "性别",
    width: "70px",
    align: "center",
    customSlot: "sex",
  }
  , {
    title: "头像",
    width: "70px",
    align: "center",
    customSlot: "userinfo",
  }, {
    title: "状态",
    customSlot: "stat",
    width: "80px", align: "center",
  },
  {
    title: "最新登录信息",
    customSlot: "logininfo",
  },
  {
    title: "操作",
    width: "180px",
    customSlot: "operator",
    key: "operator",
    align: "center",
  }
]
const dataSource = ref([])
const route = useRoute();


const avatar = (src: string) => {
  return src != null ? uploadConfig.hostURL + src : null
}
//定义模型
const putData = reactive({
  formchange: {
    id: 0,
    Status: true,
  },
  queryModel: {
    deptId: 0,
    page: page.value.current,
    limit: page.value.limit,
    nickName: "",
    userName: "",
    status: 2,
  },
  form: <User><unknown>[]
})
const { formchange, form, queryModel } = toRefs(putData)

queryModel.value.deptId = route.query.deptId as unknown as number;

const changeStatus = function (val: boolean, id: number) {
  formchange.value.id = id;
  formchange.value.Status = val;
  chStatus(formchange.value).then((res) => {
    if (res.status == 1) {
      layer.msg(res.msg, { icon: 1, time: 1000 });
    } else {
      layer.msg(res.msg, { icon: 2 });
      return false;
    }
  });
}
//获取列表
const GetList = function (query: any) {
  if (query != null) {
    queryModel.value.userName = query.userName
    queryModel.value.nickName = query.nickName
    queryModel.value.status = query.status
  }

  getList(queryModel.value).then((res) => {
    if (res.status == 1) {
      //console.log(res)
      dataSource.value = res.data
      page.value.total = res.count
    }
  })
}
const layFormRef = ref();
const reset = function () {
  layFormRef.value.reset();
}

//监听参数变化
watch(() => router.currentRoute.value.query.deptId, (deptId) => {
  queryModel.value.deptId = deptId as unknown as number
  GetList(queryModel.value)
}, { immediate: true, deep: true })

const change = function ({ current, limit }: any) {
  queryModel.value.page = current
  queryModel.value.limit = limit
  GetList(queryModel.value);
};
//修改
const edit = function (id: number) {
  changeVisible(id)
}
//添加
const add = function () {
  changeVisible(0)
}
//删除
const del = function (data: any) {
  layer.confirm("确认删除ID: " + data.id + " " + data.nickname + " 用户吗？", {
    title: "警告", move: "true", shade: "false", shadeClose: "true",
    btn: [{
      text: '确认', callback: (layerId: number) => {
        delOne(data.id).then((res) => {
          if (res.status == 1) {            
            layer.msg(res.msg, { time: 1000, icon: 1 },()=>{
              GetList(queryModel.value)
            });
          } else {
            layer.msg(res.msg, { time: 1000, icon: 2},()=>{
              
            });
          }
          layer.close(layerId);
        })
      }
    }, {
      text: '取消', callback: function (layerId: number) {
        layer.close(layerId);
      }
    }]
  })
}

//模态操作
let addoredittip = ref();

const modelVisible = ref(false)

const userGroups = ref({ targetList: [] as any, })
const userDepts = ref({ targetList: [] as any, })
const userPosts = ref({ targetList: [] as any, })

const changeVisible = function (id: number) {
  modelVisible.value = !modelVisible.value
  if (id == 0) {
    addoredittip.value = "新增用户";
    getEdit(id).then((res) => {
      if (res.status == 1) {
        userGroups.value = res.userGroups
        userDepts.value = res.userDepts
        userPosts.value = res.userPosts
        form.value = {
          id: 0,
          deptId: 0,
          gid: 0,
          postId: 0,
          username: "",
          password: "",
          nickname: "",
          status: true,
        }
      } else {
        layer.msg("获取基本信息失败！", { icon: 2 })
      }
    })

    return
  } else {
    addoredittip.value = "编辑用户";
    getEdit(id).then((res) => {
      if (res.status == 1) {
        let data = res.data
        userGroups.value = res.userGroups
        userDepts.value = res.userDepts
        userPosts.value = res.userPosts
        form.value = data

      } else {
        layer.msg("获取基本信息失败！", { icon: 2 })
      }
    })
    return
  }
}



const submitClick = function () {
  if (!form.value.username || !form.value.nickname) {
    layer.msg("用户名和姓名不能空")
    return
  }
  if (form.value.id == 0) {
    postAdd(form.value).then((res) => {
      done(res)
    });
  } else {
    putEdit(form.value).then((res) => {
      done(res)
    });
  }
};
const done = (res: any) => {
  if (res.status == 1) {
    layer.msg(res.msg, { time: 1000, icon: 1 }, () => {
      modelVisible.value = !modelVisible.value
      GetList(queryModel.value);
    });
  } else {
    layer.msg(res.msg, { icon: 2 });
    return false;
  }
}

</script>
<style scoped>
.tip {
  color: gray;
  line-height: 38px;
  height: inherit;
  padding-left: 10px;
}
</style>